#!/bin/bash

# MySQL备份脚本

DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="./backup"
MASTER_HOST="mysql-master"
MASTER_PORT=3306

# 创建备份目录
mkdir -p $BACKUP_DIR

echo "开始备份 MySQL 数据库..."
echo "备份时间: $DATE"
echo "备份目录: $BACKUP_DIR"

# 全量备份
docker exec $MASTER_HOST mysqldump -h localhost -P 3306 -u root -proot123 \
    --all-databases \
    --single-transaction \
    --routines \
    --triggers \
    --events \
    --gtid-purged=OFF \
    > $BACKUP_DIR/full_backup_$DATE.sql

if [ $? -eq 0 ]; then
    # 压缩备份文件
    gzip $BACKUP_DIR/full_backup_$DATE.sql
    
    # 删除7天前的备份
    find $BACKUP_DIR -name "*.sql.gz" -mtime +7 -delete
    
    echo "备份完成: $BACKUP_DIR/full_backup_$DATE.sql.gz"
    echo "备份大小: $(du -h $BACKUP_DIR/full_backup_$DATE.sql.gz | cut -f1)"
else
    echo "备份失败!"
    exit 1
fi
